﻿using System;
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
using HuajiTech.UnmanagedExports;
using XQ.Net.SDK;
using XQ.Net.SDK.Attributes;
using XQ.Net.SDK.Models;

namespace XQ.Net.Core.Export
{
    public class _Create
    {
        [DllExport]
        public static string XQ_Create(string frameworkversion) => CreateMain();

        public static string CreateMain()
        {

            //解析Assembly
            foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
            {
                var plugin = ass.GetCustomAttribute<XQPluginAttribute>();
                if (plugin != null)
                {
                    PluginInitializer.Init(ass);

                    _Main.xqapi.SetAppInfo(new XQ.Net.SDK.Models.AppInfo()
                    {
                        name = plugin.Name,
                        pver = plugin.Version,
                        sver = plugin.sdkv,
                        author = plugin.Author,
                        desc = plugin.Desc
                    });
                    XQAPI.AppDir = Directory.GetCurrentDirectory() + "\\Config" + "\\" + plugin.Name + "\\";
                    if (!Directory.Exists(XQAPI.AppDir))
                        Directory.CreateDirectory(XQAPI.AppDir);

                    return JsonSerializer.Serialize(new PluginInfo()
                    {
                        name = plugin.Name,
                        pver = plugin.Version,
                        sver = plugin.sdkv,
                        author = plugin.Author,
                        desc = plugin.Desc
                    }, new JsonSerializerOptions() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
                }
            }

            //throw new Exception("未找到相关程序集");
            return JsonSerializer.Serialize(new PluginInfo()
            {
                name = "XQ.Net.Test",
                pver = "1.0.0",
                sver = 3,
                author = "Heer",
                desc = "测试用-错误-Create函数"
            });
        }
    }
}